package pnu.ssm.sbmother;

import java.util.ArrayList;
import java.util.List;

import pnu.ssm.adapter.ChildListAdapter;
import pnu.ssm.appinfo.Child;
import pnu.ssm.http.HttpConnectorParent;
import pnu.ssm.key.Key;
import android.app.*;
import android.content.*;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.*;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class SelectActivity extends Activity {

	public static final String TAG = "SelectActivity";
	private static final int NOTIFY_ADAPTER = 0;

	private ArrayList<Child> childList;
	private ListView childListView;
	private ChildListAdapter childListAdapter;
	private Button btnAndroidUpdateChildList;

	private HttpConnectorParent httpConnector;
	private SharedPreferences pref;
	private SharedPreferences.Editor editor;

	private ProgressDialog progressDialog;
	private String parent_num;

	Handler selectHandler = new Handler(Looper.getMainLooper()) {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case NOTIFY_ADAPTER:
				childListAdapter.notifyDataSetChanged();
				break;
			default:
				Log.e(TAG, "handler error " + msg.what);
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_select);
		buildComponents();
		setupEventListeners();
		loadChildList();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_child_select, menu);
		ActionBar actionBar = getActionBar();
		actionBar.setTitle("목록");
		actionBar.setHomeButtonEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(true);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case R.id.menu_child_select_setting :
			Intent activity = new Intent(getApplicationContext(), SettingActivity.class);
			startActivity(activity);
			break;
		case android.R.id.home :
			showLogoutDialog();
			break;
		}

		return super.onOptionsItemSelected(item);
	}
	
	private void showLogoutDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this)
		.setTitle("로그아웃 할까요 ?")
		.setCancelable(true)
		.setPositiveButton("확인", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				SharedPreferences pref = getSharedPreferences(Key.prefKey, Context.MODE_PRIVATE);
				SharedPreferences.Editor edit = pref.edit();
				edit.putString(Key.parent_num, "");
				edit.commit();
				Toast.makeText(getApplicationContext(), "로그아웃 하였습니다.", Toast.LENGTH_LONG).show();
				
				Intent activity = new Intent(getApplicationContext(), LoginActivity.class);
				activity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(activity);
			}
		})
		.setNegativeButton("취소", null);
		
		builder.create().show();
	}

	private void buildComponents() {
		this.childList = new ArrayList<Child>();
		this.childListView = (ListView) findViewById(R.id.lv_androidChildList);
		this.childListAdapter = new ChildListAdapter(this,
				R.layout.row_select_child, childList);
		this.childListView.setAdapter(childListAdapter);
		this.btnAndroidUpdateChildList = (Button) findViewById(R.id.btn_androidUpdateChildList);

		this.httpConnector = HttpConnectorParent.getInstance();
		this.httpConnector = HttpConnectorParent.getInstance();
		this.pref = getSharedPreferences(Key.prefKey, Context.MODE_PRIVATE);
		this.editor = pref.edit();
		this.progressDialog = new ProgressDialog(this);
		this.progressDialog.setMessage("Wait...");
		this.progressDialog.setCancelable(false);
		this.progressDialog.setIndeterminate(true);

	}

	private void loadChildList() {
		Key.SELECTED_CHILD_NUM = null;
		parent_num = pref.getString(Key.parent_num, "");
		new SelectAsyncTask(parent_num, childList).execute(null, null, null);
	}

	private void setupEventListeners() {
		childListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(SelectActivity.this,
						MainActivity.class);
				String child_num = childListAdapter.getChildNum(position);
				String child_type = childListAdapter.getChildType(position);
				intent.putExtra("child_type", child_type);
				
				Key.SELECTED_CHILD_NUM = child_num;
				editor.putString(Key.child_num, child_num);
				editor.commit();
				
				startActivity(intent);
			}
		});
		btnAndroidUpdateChildList
				.setOnClickListener(new Button.OnClickListener() {
					public void onClick(View arg0) {
						new SelectAsyncTask(parent_num, childList).execute(
								null, null, null);
					}
				});
	}

	class SelectAsyncTask extends AsyncTask<Void, Void, Void> {
		String parent_num;
		ArrayList<Child> childList;

		public SelectAsyncTask(String parent_num, ArrayList<Child> childList) {
			this.parent_num = parent_num;
			this.childList = childList;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			List<Child> tempChildList = httpConnector.getChildList(parent_num);
			childList.clear();
			for (Child child : tempChildList)
				childList.add(child);
			selectHandler.sendEmptyMessage(NOTIFY_ADAPTER);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
		}
	}
}
